package com.drm.netschool.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.drm.common.util.ConfigUtil;
import com.drm.common.util.CookieUtil;
import com.drm.common.util.NumberUtil;
import com.drm.common.util.Saltcheckutil;
import com.drm.common.util.StringUtil;
import com.drm.common.util.constants.Constants;
import com.drm.netschool.entity.DrmUser;
import com.drm.netschool.redis.RedisUtil;
import com.drm.netschool.service.DrmSystemSettingService;
import com.drm.netschool.service.DrmUserCacheService;
import com.drm.netschool.service.DrmUserService;
import com.drm.netschool.service.DrmUserUlogService;
import com.drm.netschool.web.form.LoginForm;

/**
 * Created by CUIJB on 2015年7月25日
 */
@Controller
@RequestMapping("/member/")
public class LoginController {
	
	private Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private DrmUserService userService;
	
	@Autowired
	private DrmUserUlogService userUlogService;
	
	@Autowired
	private DrmUserCacheService userCacheService;
	
	@Autowired
	private DrmSystemSettingService systemSettingService;
	
	@Autowired
	private RedisUtil redisUtil;
	
	@RequestMapping(value = "user-cache", method = RequestMethod.GET)
	@ResponseBody
	public Map <String ,Map> getUser(HttpServletRequest request, HttpServletResponse response){
		CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
		//REDIS缓存
    	DrmUser user = null;
    	Map <String ,Map> result = new HashMap<String ,Map>();
    	try {
    		if(!StringUtil.empty(key))
    		{
    			user = userCacheService.getUserCache(key);
    		}
    		// tsw  2015年9月24日  输出的信息太多了
        	Map<String ,String>   data = new HashMap<String ,String>();
        	result.put("drmUser", data);
        	data.put("u", user.getUserId().toString());
        	data.put("m", user.getUserLnm());
        	data.put("img", user.getUserHimg());
		} catch (Exception e) {
			LOGGER.error("获取用户缓存信息异常", e);
		}
		return result;
	}
	
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(@ModelAttribute("form") LoginForm form, HttpServletRequest request, HttpServletResponse response) {
    	form.setMetaInfo(systemSettingService.getDrmSystemSetting());
        return "login/login";
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String doLogin(@ModelAttribute("form") LoginForm form, HttpServletRequest request, HttpServletResponse response) {
    	form.setMetaInfo(systemSettingService.getDrmSystemSetting());
    	try {
        	//登录校验
    		DrmUser user = check(form, request, response);
        	if(form.hasError()){
        		return "login/login";
        	}
        	//缓存处理
        	String key = userCacheService.setUserCache(user);
        	//登录日志
        	userUlogService.updateLoginTime(user.getUserId());
        	//cookie 处理
        	CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
    		cookieUtil.setCookie(Constants.COOKIE_USER_ID, key, ConfigUtil.getString("cookie.path"), NumberUtil.parseInteger(ConfigUtil.getString("cookie.times"), 60*60*12),false);
    		
    		//写入  匹配的  key验证
    		String keyPk = CookieUtil.getUidpk(key);
    		cookieUtil.setCookie(Constants.COOKIE_USER_ID_PK, keyPk, ConfigUtil.getString("cookie.path"), NumberUtil.parseInteger(ConfigUtil.getString("cookie.times"), 60*60*12),false);
    		 
    		
    		LOGGER.info(form.getUserName() + ",用户登录");
		} catch (Exception e) {
			LOGGER.error(form.getUserName() + ",登录异常!" , e);
			form.putError("userLogin", "系统异常!");
			return "login/login";
		}
        return getRedirectURL(form.getRedirectURL());
    }
    
    @RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(@ModelAttribute("form") LoginForm form, HttpServletRequest request, HttpServletResponse response) {
    	form.setMetaInfo(systemSettingService.getDrmSystemSetting());
    	CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_ID,false);
		//清除REDIS缓存
		userCacheService.delUserCache(key);
		//清除cookie
		cookieUtil.removeCokie(Constants.COOKIE_USER_ID);
		cookieUtil.removeCokie(Constants.COOKIE_USER_ID_PK);
	 
		return "redirect:/";
	}
    
    
    /****************** private *********************/
    
    private String getRedirectURL(String redirectURL) {
        return "redirect:" + (StringUtils.isBlank(redirectURL) ? Constants.DOMAIN : redirectURL);
    }
    
    /**
     * 登录校验
     * @param form
     * @param request
     * @param response
     * @return
     */
    private DrmUser check(LoginForm form, HttpServletRequest request, HttpServletResponse response){
    	if(StringUtil.empty(form.getUserName())){
    		form.putError("userName", "用户名不能为空");
    		return null;
    	}
    	if(StringUtil.empty(form.getPassword())){
    		form.putError("password", "密码不能为空");
    		return null;
    	}
    	CookieUtil cookieUtil = new CookieUtil(request, response, ConfigUtil.getString("cookie.domain"));
    	String key = cookieUtil.getCookie(Constants.COOKIE_USER_CHECKCODE );
    	String sRand = redisUtil.getString(StringUtil.empty(key) ? "" : key);
    	if(!sRand.equals(form.getCheckCode())){
    		form.putError("checkCode", "校验码有误");
    		return null;
    	}
    	DrmUser user = userService.getByUserName(form.getUserName());
    	if(user == null || StringUtil.empty(user.getUserLnm())){
    		form.putError("userLogin", "用户名未注册");
    		return null;
    	}
    	if (user.getUserAvtive() == 0) {
    		form.putError("userLogin", "账号未激活，请去邮箱激活");
            return null;
		}
    	if (NumberUtil.parseInteger(user.getUserTp()) != 5 && NumberUtil.parseInteger(user.getUserTp()) != 3) {
    		form.putError("userLogin", "用户类型有误");
            return null;
		}
    	String pwd = Saltcheckutil.saltArithmetic(form.getPassword(), user.getUserSalt());
		if(!pwd.equals(user.getUserPass())){
			form.putError("userLogin", "密码有误");
    		return null;
		}
		return user;
    }
}
